package com.fr.elastic;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

public class WriteEsTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client =
            new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        FileReader fr = new FileReader("/Users/furong/Documents/test.txt");
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();
        long count = 1;
        BulkRequest request = new BulkRequest();
        while (line != null) {
            IndexRequest index = new IndexRequest("my_test");
            Map<String, Object> source = new HashMap<>();
            source.put("line", count);
            source.put("text", line);
            index.source(source);
            index.id(String.valueOf(count));
            request.add(index);
            if (request.numberOfActions() > 1000) {
                client.bulk(request, RequestOptions.DEFAULT);
                request = new BulkRequest();
            }
            count++;
            line = br.readLine();
        }
        if (request.numberOfActions() > 0) {
            client.bulk(request, RequestOptions.DEFAULT);
        }
        br.close();
        fr.close();
        client.close();
    }

}
